package com.kk.base.service.home;

import com.kk.base.bean.PageBean;
import com.kk.base.dao.home.HomeUserDao;
import com.kk.base.entity.home.HomeUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

/**
 * 前台前台用户业务处理层
 */
@Service
public class HomeUserService {
    
    @Autowired
    private HomeUserDao homeUserDao;
    

    /**
     * 根据前台用户id查询
     * @param id
     * @return
     */
    public HomeUser find(Long id){
        return homeUserDao.find(id);
    }

    /**
     * 按照前台用户名查找前台用户
     * @param name
     * @return
     */
    public HomeUser findByName(String name){
        return homeUserDao.findByName(name);
    }

    /**
     * 按手机号查找
     * @param mobile
     * @return
     */
    public HomeUser findByMobile(String mobile){
        return homeUserDao.findByMobile(mobile);
    }


    /**
     * 前台用户添加/编辑操作
     * @param homeUser
     * @return
     */
    public HomeUser save(HomeUser homeUser){
        return homeUserDao.save(homeUser);
    }

    /**
     * 分页查询前台用户列表
     * @param homeUser
     * @param pageBean
     * @return
     */
    public PageBean<HomeUser> findList(HomeUser homeUser, PageBean<HomeUser> pageBean){
        ExampleMatcher withMatcher = ExampleMatcher.matching().withMatcher("mobile", ExampleMatcher.GenericPropertyMatchers.contains());
        withMatcher = withMatcher.withIgnorePaths("sex","status");
        Example<HomeUser> example = Example.of(homeUser, withMatcher);
        Pageable pageable = PageRequest.of(pageBean.getCurrentPage()-1, pageBean.getPageSize());
        Page<HomeUser> findAll = homeUserDao.findAll(example, pageable);
        pageBean.setContent(findAll.getContent());
        pageBean.setTotal(findAll.getTotalElements());
        pageBean.setTotalPage(findAll.getTotalPages());
        return pageBean;
    }



    /**
     * 判断前台用户手机号是否存在，添加和编辑均可判断
     * @param mobile
     * @param id
     * @return
     */
    public boolean isExistMobile(String mobile,Long id){
        HomeUser homeUser = homeUserDao.findByMobile(mobile);
        if(homeUser != null){
            //表示前台用户名存在，接下来判断是否是编辑前台用户的本身
            if(homeUser.getId().longValue() != id.longValue()){
                return true;
            }
        }
        return false;
    }

    /**
     * 按照前台用户id删除
     * @param id
     */
    public void delete(Long id){
        homeUserDao.deleteById(id);
    }

    /**
     * 返回前台用户总数
     * @return
     */
    public long total(){
        return homeUserDao.count();
    }

    
    
}
